package com.auxgroup.smarthome.enterprise.service;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.appconst.AppConstant;
import com.auxgroup.smarthome.enterpriseapi.EnterpriseApi;
import com.auxgroup.smarthome.enterpriseapi.requestbody.AssociationInfoBody;
import com.auxgroup.smarthome.enterpriseapi.requestbody.DeviceAggDataBody;
import com.auxgroup.smarthome.enterpriseapi.requestbody.GetTokenBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.AggDataResult;
import com.auxgroup.smarthome.enterpriseapi.responsebody.ProductAccessToken;
import com.auxgroup.smarthome.enterpriseapi.responsebody.ProductList;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.utils.common.LOG;
import com.auxgroup.smarthome.web.ApiResponse;
import javassist.NotFoundException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by kevinchen on 2017/3/11.
 */
@Service
public class ProductService {

    @Autowired
    private ObjectRedis objectRedis;

    @Autowired
    private EnterpriseService enterpriseService;




    public String getProductSecret(String productKey){
        return AppConstant.PRODUCT_KEY_SECRET_MAP.get(productKey);
    }

    /**
     * 获取对应pk的企业API token
     * 支持缓存 缓存时长5天
     * @param productKey
     * @return 对象token
     * @throws Exception
     */
    public ProductAccessToken getProductAccessToken(String productKey) throws Exception {
        String productSecret = getProductSecret(productKey);
        if(productSecret == null){
            throw new NotFoundException("Not find ProductSecret,ProductKey is " + productKey);
        }
        String cacheAccessTokenPath = "product_access_token/"+productKey;
        ProductAccessToken accessToken = objectRedis.get(cacheAccessTokenPath,ProductAccessToken.class);

        if(accessToken == null || System.currentTimeMillis()/1000 > accessToken.getExpire_at()){
            GetTokenBody getTokenBody = new GetTokenBody(enterpriseService.getEnterpriseId(),enterpriseService.getEnterpriseSecret(),productSecret);
            accessToken = EnterpriseApi.ProcuctManagement.getProductToken(productKey,getTokenBody);
            if(accessToken != null && accessToken.getToken() != null){
                objectRedis.add(cacheAccessTokenPath,5*24*60L,accessToken);
            }
            else {
                throw new Exception("Enterprise token get failed,ProductKey is " + productKey);
            }
        }
        return accessToken;
    }


    /**
     * 获取某一产品的token
     * 简化版本
     * @param productKey
     * @return 字符串token
     */
    public String getToken(String productKey) {
        ProductAccessToken productAccessToken;
        try {
            productAccessToken = getProductAccessToken(productKey);
        } catch (Exception e) {
            LOG.error(this,e.getMessage());
            throw new IllegalArgumentException(e.getMessage());
        }
        return productAccessToken.getToken();
    }

    /**
     * 产品列表
     * 获取该企业下的所有产品
     * 支持缓存 缓存市场 5天
     * @return
     */
    public ProductList getProductList() {
        ProductList productList = objectRedis.get("product_list",ProductList.class);
        if(productList == null){
            productList = EnterpriseApi.ProcuctManagement.getProductList(enterpriseService.getEnterpriseId(), enterpriseService.getEnterpriseSecret());
            if(StringUtils.isNotEmpty(productList.getError_code())) {
                return null;
            }
            objectRedis.add("product_list",5*24*60L,productList);
        }
        return productList;
    }

    /**
     * 获取产品数据点
     *
     * @param pk
     * @return
     */
    public JSONObject getProductPoint(String pk) {
        return EnterpriseApi.ProcuctManagement.getProductPoint(getToken(pk), pk);
    }


    /**
     * 获取wifi聚合数据
     *
     * @param pk
     * @param did
     * @param body
     * @return
     */
    public ApiResponse<AggDataResult> wifiDeviceAggData(String pk, String did, DeviceAggDataBody body) {
        AggDataResult  resultResponse = EnterpriseApi.wifiDeviceAggData(getToken(pk), pk, did, body);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);

    }

    /**
     * 关联产品
     * @param pk
     * @param eid
     * @param eSecret
     * @return
     */
    public JSONObject associationProduct(String pk, String eid, String eSecret, String pkSecret) {
        return EnterpriseApi.ProcuctManagement.associationProduct(pk, new AssociationInfoBody(eid, eSecret, pk));
    }

//    /**
//     * 获取 产品关联的应用信息
//     * @param pk
//     * @return
//     */
//    public ApplicationInfo getApplication(String pk){
//        return EnterpriseApi.ProcuctManagement.getApplication(getToken(pk), pk, 20, 0);
//    }


}
